<template>
  <view class="home">
    <!-- 导航栏 -->
    <view class="topnav" style="width: 240rpx;">
      <u-tabs :list="navList" :is-scroll="false" v-model="current" @change="tabSwitch"></u-tabs>
    </view>
    <!-- 骨架屏 -->
    <!-- 内容 -->
    <view class="content ">
      <view class="item" v-for="(itemDate,index) in dataList" :key="index">
        <blog-item :item="itemDate" @delEvent="on_delEvent"></blog-item>
      </view>
    </view>
    <!-- 编辑图标 -->
    <view class="edit" @click="goEdit">
      <text class="iconfont icon-a-21-xiugai"></text>
    </view>
    <uni-load-more :status="load_more"></uni-load-more>
  </view>
</template>

<script>
  import {
    onMounted,
    ref,
    watch
  } from "vue"
  import {
    useStore
  } from 'vuex'
  import {
    onReachBottom,
    onLoad
  } from '@dcloudio/uni-app'
  import {
    goLoginPage
  } from '../../utils/tools.js'
  import {
    store
  } from "../../uni_modules/uni-id-pages/common/store.js"
  const db = uniCloud.database()
  const dbCmd = db.command
  export default {
    setup() {
      const vuex_store = useStore()
      // 通过vuex监听同级组件 实现点赞联动
      watch(() => vuex_store.getters.watch_cellback_detail_like, (val, old) => {
        console.log("watch")
        dataList.value.forEach(item => {
          if (val._id._value == item._id) {
            val._state ? item.like_count++ : item.like_count--
            item.isLike = val._state
          }
        })
      }, {
        deep: true
      })
      // 通过vuex监听同级组件 实现评论数量
      watch(() => vuex_store.getters.watch_cellback_del_comment, (val, old) => {
        console.log("watch")
        dataList.value.forEach(item => {
          if (val._id == item._id) {
            if (val._state) {
              item.comment_count += 1
            } else {
              item.comment_count -= val.num
            }
          }
        })
      }, {
        deep: true
      })
      const current = ref(0)
      const navList = ref([{
        name: '最新',
        type: "last_modify_date"
      }, {
        name: '热门',
        type: 'view_count'
      }])
      const navList_state = ref(0)
      const dataList = ref([])
      const load_more = ref("loading")
      const load_more_state = ref(true)

      // 导航栏切换触发
      const tabSwitch = (e) => {
        dataList.value = []
        navList_state.value = e
        load_more.value = "loading"
        load_more_state.value = true
        getDate(e)
      }
      // 触底加载
      onReachBottom(() => {
        if (load_more_state.value) {
          load_more.value = "loading"
          getDate(navList_state.value)
        }
      })
      // 页面无感删除文章
      const on_delEvent = (_id) => {
        dataList.value = dataList.value.filter(item => item._id != _id)
      }
      // 获取后台数据
      const getDate = async (index) => {
        // 连表查询
        let artTamp = db.collection("pyq_article").where(`delState != true`).field(
            "title,user_id,description,picurls,comment_count,like_count,view_count,publish_date,last_modify_date")
          .getTemp()
        let userName = db.collection("uni-id-users").field("_id,username,nickname,avatar_file").getTemp()

        let res = await db.collection(artTamp, userName).orderBy(navList.value[index].type, "desc").skip(dataList
            .value
            .length)
          .limit(6).get()
        let resDate = res.result.data
        if (!res.result.data.length) {
          load_more_state.value = false
          load_more.value = "noMore"
        }
        let idArr = []
        // 获取所有点赞_id
        resDate.forEach(item => {
          idArr.push(item._id)
        })
        let uid_like_arr = await db.collection("pyq_like").where({
          // 获取所有点赞
          article_id: dbCmd.in(idArr),
          // 过滤 得到当前用户点赞的文章
          user_id: uniCloud.getCurrentUserInfo().uid
        }).get()
        // 用当前用户点赞的id，跟返回来的数组中_id一一匹配，如果匹配成功就说明该文章用户已经点赞了
        uid_like_arr.result.data.forEach(item => {
          let findIndex = resDate.findIndex(find => {
            return item.article_id == find._id
          })
          resDate[findIndex].isLike = true
        })

        dataList.value = [...dataList.value, ...resDate]
      }

      // 初始化获取数据
      onLoad(() => {
        getDate(current.value)
        // console.log("B 页面 onLoad:", option); //B 页面 onLoad: {id: '1', name: 'uniapp'}？
      })
      // 跳转到编辑
      const goEdit = () => {
        console.log(store)
        if (store.hasLogin) {
          uni.navigateTo({
            url: "/pages/edit/edit"
          })
        } else {
          goLoginPage()
        }
      }
      return {
        navList,
        current,
        tabSwitch,
        dataList,
        goEdit,
        load_more,
        on_delEvent
      }
    }
  }
</script>

<style lang="scss" scoped>
  .edit {
    width: 120rpx;
    height: 120rpx;
    background-color: #0199EF;
    color: #fff;
    position: fixed;
    z-index: 99;
    bottom: 150rpx;
    right: 50rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: 0 0 20rpx rgba(1, 153, 254, 0.8);
    border-radius: 60rpx;

    .iconfont {
      font-size: 50rpx;
    }
  }

  .loadingSate {
    padding: 20rpx 20rpx;
  }

  .content {
    .item {
      padding: 24rpx;
      border-bottom: #F7f7f7 10rpx solid;
    }
  }
</style>